package com.yfp.auth.controller;

import com.yfp.auth.domain.Machine;
import com.yfp.auth.mapper.MachineMapper;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.JwtUtils;
import com.yfp.common.core.utils.StringUtils;
import com.yfp.common.security.auth.AuthUtil;
import com.yfp.common.security.service.TokenService;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.system.api.domain.SysUser;
import com.yfp.system.api.model.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

@RestController
@Slf4j
public class MachineTokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private MachineMapper machineMapper;

    /**
     * 设备登录 获取token
     *
     * @param machineSn        机器编号
     * @param base64MachinePwd 机器密码
     * @return token
     */
    @PostMapping("machineLogin")
    public R<Map<String, Object>> machineLogin(@RequestParam String machineSn, @RequestParam String base64MachinePwd) {
        try {
            log.info("machineLogin:{};base64MachinePwd:{}", machineSn, base64MachinePwd);
            // 设备登录 认证
            Machine machine = machineMapper.selectByPrimaryKey(machineSn);
            if (machine != null && base64MachinePwd != null) {
                String machinePwd = new String(Base64.getDecoder().decode(base64MachinePwd), StandardCharsets.UTF_8);
                boolean checkPwd = machinePwd.equals(machineSn + machineSn);
                if (checkPwd) {
                    // 获取登录token
                    LoginUser loginUser = new LoginUser();
                    loginUser.setSysUser(new SysUser());
                    loginUser.getSysUser().setUserId(Long.parseLong(machineSn));
                    loginUser.getSysUser().setUserName(machineSn);
                    Map<String, Object> tokenMap = tokenService.createToken(loginUser);
                    tokenMap.put("tempFrequency", null == machine.getTempFrequency() ? 1 :machine.getTempFrequency());
                    return R.ok(tokenMap);
                }
            }
            return R.fail("设备认证失败");
        } catch (Exception e) {
            log.error("设备认证失败", e);
            return R.fail("设备认证失败");
        }
    }

    /**
     * 设备登出
     *
     * @param request 请求体
     * @return 响应体
     */
    @DeleteMapping("machineLogout")
    public R<?> machineLogout(HttpServletRequest request) {
        try {
            String token = SecurityUtils.getToken(request);
            if (StringUtils.isNotEmpty(token)) {
                String machineSn = JwtUtils.getUserName(token);
                log.info("machineLogout:{}", machineSn);
                // 删除用户缓存记录
                AuthUtil.logoutByToken(token);
            }
            log.info("设备登出成功");
            return R.ok("设备登出成功");
        } catch (Exception e) {
            log.error("设备登出失败", e);
            return R.fail("设备登出失败");
        }
    }

    /**
     * 设备token刷新
     *
     * @param request 请求头
     * @return 响应体
     */
    @PostMapping("machineRefresh")
    public R<?> machineRefresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok("设备刷新令牌成功");
        }
        return R.fail("设备刷新令牌失败");
    }

}
